﻿using MediaInfoDotNet;
using SimpleConnection_UDP_WIN.utils;
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using VideoMergeSplitApp.data;
using VideoMergeSplitApp.utils;
using WindowsImageCompressionApp.utils;

namespace VideoMergeSplitApp.ui
{
    public partial class BatchCompressionOfVideos : Form
    {

        ArrayList videoList = new ArrayList();

        public BatchCompressionOfVideos()
        {
            InitializeComponent();
        }

        private void BatchCompressionOfVideos_Load(object sender, EventArgs e)
        {

        }


        private void listView1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }

        private void listView1_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (string filePath in files)
            {
                addList(filePath);
            }
        }

        //添加数据到 list和 列表
        public void addList(string filePath)
        {

            FileInfo fileInfo = new FileInfo(filePath);

            if (!fileInfo.IsReadOnly)
            {
                //添加 list 数据
                videoList.Add(filePath);

                MediaFile mediaFile = new MediaFile(filePath);
                string resolution = mediaFile.Video[0].Width + "x" + mediaFile.Video[0].Height;

                // 添加列表项
                ListViewItem item1 = new ListViewItem(fileInfo.Name); // 第一列的值
                item1.SubItems.Add(fileInfo.Extension); // 添加其他列的值

                TimeSpan duration = TimeSpan.FromMilliseconds(mediaFile.Video[0].duration); // 将毫秒转换为TimeSpan对象

                item1.SubItems.Add($"{duration.Hours}:{duration.Minutes}:{duration.Seconds}"); // 添加其他列的值
                item1.SubItems.Add(DBUtil.FormatFileSize(fileInfo.Length)); // 添加其他列的值
                item1.SubItems.Add("未知"); // 添加其他列的值

                listView1.Items.Add(item1);
            }


        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (videoList.Count <= 0)
            {
                MessageBox.Show("请先选择要压缩的视频", "提示");
                return;
            }

            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog
            {
                RootFolder = Environment.SpecialFolder.Desktop
                ,
                ShowNewFolderButton = true
                ,
                Description = "请选择输出目录"

            };

            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                string dir = folderBrowserDialog.SelectedPath;

                if (!string.IsNullOrWhiteSpace(dir))
                {
                    button1.Enabled = false;
                    textBox1.Enabled = false;
                    listView1.Enabled = false;
                    checkBox1.Enabled = false;
                    toolStripProgressBar1.Value = (int)(100f / videoList.Count / 3);

                    Task.Run(() =>
                    {
                        foreach (string path in videoList)
                        {

                            this.Invoke(new Action(() =>
                            {
                                toolStripStatusLabel2.Text = $"正在使用硬件加速压缩第 {videoList.IndexOf(path) + 1} 个视频";
                            }));

                            FileInfo fileInfo = new FileInfo(path);
                            string fileName = fileInfo.Name;
                            string fileExtension = fileInfo.Extension;

                            string comPath = Path.Combine(dir, "comp_" + fileName);

                            string ffcmd = $" -hwaccel cuvid -c:v h264_cuvid -i \"{path}\" -c:v h264_nvenc -b:v {textBox1.Text}M \"{comPath}\"";

                            if (!checkBox1.Checked)
                            {
                                //非硬件编码
                                 ffcmd = $" -i \"{path}\" -b:v {textBox1.Text}M \"{comPath}\"";
                            }

                            Console.WriteLine("压缩命令：" + ffcmd);
                            CmdUtil.RunFFCmd(ffcmd);

                            this.Invoke(new Action(() =>
                            {
                                listView1.Items[videoList.IndexOf(path)].SubItems[4].Text = DBUtil.FormatFileSize(new FileInfo(comPath).Length);
                                toolStripProgressBar1.Value = (int)((float)(videoList.IndexOf(path) + 1) / (float)videoList.Count * 100);
                            }));

                        }

                        this.Invoke(new Action(() =>
                        {

                            toolStripStatusLabel2.Text = $"处理完成，共 {videoList.Count} 个文件";
                            button2.Visible = true;


                            Form1 form1 = new Form1();
                            if (form1.menuItem8.Checked)
                                SoundUtil.playReminderTone();

                            MessageBox.Show($"压缩完成，请自行查看文件完整性，共导出 {videoList.Count} 个新文件", "提示");

                            if (form1.menuItem2.Checked)
                            {
                                DBUtil.openExplorerDir(new FileInfo(dir).DirectoryName);
                                form1.Dispose();
                            }

                        }));
                    });

                }
            }

        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b') // 判断输入的字符是否为数字或退格键
            {
                if (e.KeyChar != '.')
                {
                    e.Handled = true; // 阻止输入
                }

            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            MessageBox.Show($"保证比特率在1-3M以内最为合适，但对于较小的视频文件，比特率要降低到0.3甚至更低才会起作用，比特率越低，文件体积越小，同时画质会更模糊\n\n请一定按照规范填写比特率\n\n请保证选择的输出目录，没有和被压缩的视频同名的文件", "提示");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            button1.Enabled = true;
            textBox1.Enabled = true;
            listView1.Enabled = true;
            button2.Visible = false;
            checkBox1.Enabled = true;

            listView1.Items.Clear();
            videoList.Clear();

            toolStripStatusLabel2.Text = string.Empty;
            toolStripProgressBar1.Value = 0;

        }

       
    }
}
